package com.bv.hr.system.controller;

import com.bv.hr.common.core.http.HttpResult;
import com.bv.hr.common.utils.IoUtils;
import com.bv.hr.common.utils.PasswordUtils;
import com.bv.hr.system.dto.LoginBean;
import com.bv.hr.system.entity.User;
import com.bv.hr.system.security.JwtAuthenticationToken;
import com.bv.hr.system.service.LoginLogService;
import com.bv.hr.system.service.UserService;
import com.bv.hr.system.util.IpUtils;
import com.bv.hr.system.util.SecurityUtils;
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * @author CYT7
 * @version 1.0
 * @time 12月 21,2021
 * @describe 登录控制器
 */
@RestController
@Slf4j
@RequiredArgsConstructor
public class LoginController{
    private final Producer producer;
    private final UserService userService;
    private final LoginLogService loginLogService;
    private final AuthenticationManager authenticationManager;

    /**
     * @describe 生成验证码
     */
    @GetMapping("captcha")
    public void captcha(HttpServletResponse response, HttpServletRequest request) throws IOException {
        response.setHeader("Cache-Control","no-store,no-cache");
        response.setContentType("image/jpeg");
        //生成文字验证码
        String text = producer.createText();
        //生成图片验证码
        BufferedImage image = producer.createImage(text);
        //保存验证码到session
        request.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY,text);
        ServletOutputStream outputStream = response.getOutputStream();
        ImageIO.write(image,"jpg",outputStream);
        IoUtils.closeQuietly(outputStream);
    }
    /**
     * 用户登录
     * @param loginBean 用户登录配置
     * @param request http请求
     * @return token
     */
    @PostMapping("/login")
    public HttpResult login(@RequestBody LoginBean loginBean,HttpServletRequest request) {
        String username = loginBean.getUsername();
        String password = loginBean.getPassword();
        String captcha = loginBean.getCaptcha();
        //从session中获取之前保存的验证码跟前台传来的验证码进行匹配
        Object kappa = request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
        if (kappa == null){
            return HttpResult.error("验证码已失效");
        }
        if(!captcha.equals(kappa)){
            return HttpResult.error("验证码不正确");
        }
        //用户信息
        User user = userService.findByName(username);
        //账号不存在、密码错误
        if (user == null){
            return HttpResult.error("账号不存在");
        }
        if (PasswordUtils.matchPassword(user.getSalt(),password,user.getPassword())){
            return HttpResult.error("密码不正确");
        }
        //账号锁定
        if (user.getStatus() == 0) {
            return HttpResult.error("账号已经被锁定，请联系管理员");
        }
        //系统登录认证
        JwtAuthenticationToken token = SecurityUtils.login(request, username, password, authenticationManager);
        //记录登录日志
        loginLogService.writeLoginLog(username, IpUtils.getIpAddr(request));
        return HttpResult.ok(token);
    }
}
